import {Http} from '@angular/http';
import {NgLayer, NgLayerRef} from 'ng2-layer';
import {Component,ViewContainerRef, Injectable}  from '@angular/core';
import {ActivatedRoute} from '@angular/router';
import {FormsModule}  from '@angular/forms';
/**
 * 左侧菜单部分
 */
@Component({
	selector: '.box_address',
	templateUrl: 'template/router/boxSetting/address.html'
})
export class BoxAddressComp {
	addresses:any;
	constructor(
	private http:Http,
	router:ActivatedRoute,
	private layer:NgLayer,
	private parent:ViewContainerRef){
		router.parent.params.subscribe(params => {
			this.boxId = params.id;
			
			//获取盒子详细信息
			http.get({
				search:{
					m:"Admin",
					c:"ApiBox",
					a:"getBoxAddressConfig",
					box_id:this.boxId
				}
			}).then((data)=>{
				this.addresses = data.data.data;
				
				this.addresses.forEach((adr)=>{
					adr.option = adr.option==0?false:true;
				});
			})
		});
	}
	
	/**
	 * 删除地址
	 */
	deleteAdr(adr){
		let adrs = this.addresses.filter((i)=>{
			return i!==adr;
		});
		this.saveAddress(adrs, ()=>{
			this.addresses = adrs;
		});
	}
	
	/**
	 * 保存地址
	 */
	saveAddress(adrs, callBack){
		if(!adrs){
			adrs = this.addresses.slice();
		}
		adrs.forEach((adr)=>{
			adr.option = adr.option?1:0;
		})
		
		this.http.post({
			search:{
				m:"Admin",
				c:"ApiBox",
				a:"setBoxOpenAddress"
			},
			body:{
				is_address_open:"open",
				address:JSON.stringify(adrs),
				box_id:this.boxId
			}
		}).then((data)=>{
			callBack?callBack():'';
		})
	}
	
	/**
	 * 弹出添加地址对话框
	 */
	addAddress(){
		let ly = this.layer.dialog({
			title:"添加可送地址",
			parent:this.parent,
			dialogComponent:AddAddressComp,
			imports:[FormsModule],
			data:{addresses:this.addresses, boxId:this.boxId, parent:this}
		});
	}
}

@Component({
	templateUrl:"template/dialog/addAddress.html"
})
class AddAddressComp {
	address:any;
	addresses:any;
	boxId:any;
	parent:any;
	
	constructor(private ly:NgLayerRef, private http:Http){}
	
	cancel(){this.ly.close();};
	
	/**
	 * 
	 */
	add(){
		let adrs = this.addresses;
		
		adrs.push({
			option:1,
			address:this.address
		})
		
		adrs.forEach((adr)=>{
			adr.option = adr.option?1:0;
		})
		
		this.http.post({
			search:{
				m:"Admin",
				c:"ApiBox",
				a:"setBoxOpenAddress"
			},
			body:{
				is_address_open:"open",
				address:JSON.stringify(adrs),
				box_id:this.boxId
			}
		}).then((data)=>{
			this.parent.addresses = adrs;
			this.ly.close();
		})
	}
}
